package kr.co.pension.utils;

import java.awt.Color;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.backgrounds.FlatColorBackgroundProducer;
import nl.captcha.gimpy.DropShadowGimpyRenderer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.NumbersAnswerProducer;

public class CaptchaServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			Color backgroundColor = Color.WHITE;
			Captcha captcha = new Captcha.Builder(200, 50)
//					.addText(new DefaultTextProducer(6))
					.addBackground(new FlatColorBackgroundProducer(backgroundColor))
					.addText(new NumbersAnswerProducer(6))
		//			.addNoise()
//					.addNoise(new StraightLineNoiseProducer())
		//			.gimp(new FishEyeGimpyRenderer())
					.gimp(new DropShadowGimpyRenderer())
					.build();

			// 200 * 50 에해당하는 이미지 사이즈를 지정하고, 자동가입방지 문자 길이를 설정한다.
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			// 캐쉬를 지우기 위해 헤더값을 설정
			response.setContentType("image/jpeg");
			// 리턴값을 image형태로 설정
			CaptchaServletUtil.writeImage(response, captcha.getImage());
			// Image 를 write 한다
			request.getSession().setAttribute(Captcha.NAME,
					captcha);
			// 세션에 자동가입방지 문자를 저장한다.
		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println(e.getStackTrace());
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

	}

}
